package plus.easydo.starter.oauth.resources.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.web.AuthenticationEntryPoint;
import plus.easydo.core.result.DataResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 自定义资源服务验证失败处理
 *
 * @author yuzhanfeng
 */
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {
        Throwable cause = authException.getCause();

        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        DataResult<Object> result;
        try {
            if (cause instanceof InvalidTokenException) {
                result = DataResult.fail(HttpStatus.UNAUTHORIZED.value(), "认证失败,无效或过期token");

            } else {
                result = DataResult.fail(HttpStatus.UNAUTHORIZED.value(), "认证失败,没有携带token");
            }
            response.getWriter().write(new ObjectMapper().writeValueAsString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
